<template>
  <div class="user-manage">
    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
        <div class="item-group">
            <el-form-item label="用户名:">
                <el-input v-model="searchForm.donatorUsername" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item label="手机号:">
                <el-input v-model="searchForm.donatorPhone" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="捐赠者ID:">
                <el-input v-model="searchForm.donatorId" placeholder="请输入捐赠者ID" />
            </el-form-item>
        </div>
        <div class="btn-group">
            <el-button type="primary" @click="getDonatorList" size="small">
                <el-icon><Search /></el-icon>
                搜索
            </el-button>
            <el-button type="success" @click="handleEdit(1)" size="small">
                <el-icon><Plus /></el-icon>
                新增
            </el-button>
            <el-button type="danger" @click="handleDelete('batch')" size="small">
                <el-icon><Minus /></el-icon>
                批量删除
            </el-button>
        </div>
    </el-form>
    <!-- 表格数据 -->
    <el-table 
        :data="tableData" 
        style="width: 100%" 
        border 
        :header-cell-style="{ background: 'rgb(216,231,246)' }" 
        max-height="500"
        @selection-change="handleSelectionChange"
    >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="donatorId" label="捐赠者ID" />
        <el-table-column prop="donatorPhone" label="手机号" />
        <el-table-column prop="donatorUsername" label="用户名" />
        <el-table-column prop="donatorAvatar" label="头像">
            <template #default="scope">
                <el-image :src="imageUrl + scope.row.donatorAvatar" style="width: 50px; height: 50px" />
            </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
            <template #default="{ row }">
                <el-button link type="primary" @click="handleViewDonationRecords(row)">查看捐赠记录</el-button>
                <el-button link type="primary" @click="handleEdit(0, row)">编辑</el-button>
                <el-button link type="primary" @click="handleDelete('single', row.donatorId)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <div class="pagination">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next,jumper"
            :page-sizes="[10, 50, 100]"
            :total="total"
            v-model:page-size="pageSize"
            v-model:current-page="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
    <!-- 编辑捐赠者信息弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="400">
        <el-form :model="dialogForm" label-width="auto">
            <el-form-item label="头像:">
                <el-upload
                    ref="upload"
                    class="avatar-uploader"
                    :action="fileUrl"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :on-error="handleAvatarError"
                    :before-upload="beforeAvatarUpload"
                    :limit="1"
                >
                    <el-image v-if="dialogForm.donatorAvatar" :src="imageUrl + dialogForm.donatorAvatar" style="width: 100px; height: 100px;" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="用户名:">
                <el-input v-model="dialogForm.donatorUsername" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="手机号:">
                <el-input v-model="dialogForm.donatorPhone" placeholder="请输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="密码:">
                <el-input v-model="dialogForm.donatorPassword" placeholder="请输入密码" type="password"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="handleSure">确定</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
        </template>
    </el-dialog>
    <!-- 捐赠记录信息弹窗 -->
     <el-dialog v-model="recordDialogVisible" title="捐赠记录" width="80%" style="max-height: 80%;">
        <el-table 
            :data="donationRecordsData" 
            style="width: 100%" 
            border
            :header-cell-style="{ background: 'rgb(216,231,246)' }" 
            max-height="100%"
        >
            <el-table-column prop="donationRecordsId" label="捐赠记录ID" />
            <el-table-column prop="fundraisingProjectsName" label="募捐项目名称" />
            <el-table-column prop="agencyName" label="所属募捐机构" />
            <el-table-column prop="donationAmount" label="捐赠金额" />
            <el-table-column prop="donationTime" label="捐赠时间" :formatter="handleFormatDate" />
        </el-table>
     </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { adminApi } from '../../api/app';
import { Plus, Search, Minus } from '@element-plus/icons-vue'
import { fileUrl, imageUrl } from '../../api/request';
import { ElMessage, ElMessageBox, UploadInstance, UploadProps } from 'element-plus';
import { handleFormatDate, beforeAvatarUpload, handleAvatarError } from './ts/common';

/** 搜索表单 */
const searchForm = ref({
    donatorUsername: null,
    donatorPhone: null,
    donatorId: null,
})
/** 表格数据 */
const tableData = ref([])
/** 数据总数 */
const total = ref(0);
/** 当前页码 */
const currentPage = ref(1);
/** 每页显示条数 */
const pageSize = ref(10);
/** 多选选中内容 */
const selection = ref<any[]>([]);
/** 编辑捐赠者信息弹窗可见性 */
const dialogVisible = ref(false);
/** 编辑 | 新增弹窗标题 */
const dialogTitle = ref('');
/** 编辑 | 新增弹窗表单 */
const dialogForm = ref({
    donatorId: null,
    donatorUsername: null,
    donatorPhone: null,
    donatorAvatar: null,
    donatorPassword: null,
});
/** 捐赠记录信息弹窗可见性 */
const recordDialogVisible = ref(false);
/** 捐赠记录信息 */
const donationRecordsData = ref([]);
const upload = ref<UploadInstance>();

// 初始加载
onMounted(() => {
    // 获取用户列表
    getDonatorList();
});

/** 获取捐赠者信息列表 */
const getDonatorList = () => {
    adminApi.getDonators({ pageNum: currentPage.value, pageSize: pageSize.value, ...searchForm.value }).then((res: any) => {
        if (res) {
            tableData.value = res.records;
            total.value = res.total;
        }
    });
};

/** 多选变化 */
const handleSelectionChange = (val: any) => {
    val.forEach((element: any) => selection.value.push(element.donatorId));
};

/** 新增 | 编辑捐赠者信息 */
const handleEdit = (type: number, row?: any) => {
    dialogVisible.value = true;
    dialogTitle.value = '新增捐赠者信息';
    resetForm();
    // 编辑模式 需要给表单赋值当前行数据
    if (type === 0) {
        dialogTitle.value = '编辑捐赠者信息';
        dialogForm.value = { ...row };
    };
}

/** 重置内容 */
const resetForm = () => {
    dialogForm.value = {
        donatorUsername: null,
        donatorPhone: null,
        donatorAvatar: null,
        donatorPassword: null,
        donatorId: null,
    };
}

/** 重置弹窗内容并关闭弹窗 */
const resetDialog = () => {
    resetForm();
    dialogVisible.value = false;
    getDonatorList();
};

/** 弹窗确定 */
const handleSure = () => {
    if (dialogTitle.value === '新增捐赠者信息') {
        adminApi.addDonator(dialogForm.value).then(res => {
            if (res) {
                ElMessage.success('新增成功');
                resetDialog();
            }
        }).catch(() => {
            ElMessage.error('新增失败');
        });
    } else {
        adminApi.updateDonator(dialogForm.value).then(res => {
            if (res) {
                ElMessage.success('编辑成功');
                resetDialog();
            }
        }).catch(() => {
            ElMessage.error('编辑失败');
        });
    }
};

/** 删除捐赠者 */
const handleDelete = (control: string, donatorId?: string) => {
    ElMessageBox.confirm('确定删除吗？', '注意', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const donatorIds = control === 'single' ? [donatorId] : selection.value;
        adminApi.deleteDonators(donatorIds).then(res => {
            if (res) {
                ElMessage.success('删除成功');
                getDonatorList();
                // 批量删除清空选中内容
                if(control === 'batch') {
                    selection.value = [];
                }
            } else {
                ElMessage.error('删除失败');
            }
        });
    }).catch(() => {
        ElMessage.info('已取消');
    });
}

/** 表格分页大小改变 */
const handleSizeChange = (val: number) => {
    pageSize.value = val;
    getDonatorList();
};

/** 表格页码改变 */
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    getDonatorList();
};

/** 上传头像成功 */
const handleAvatarSuccess: UploadProps['onSuccess'] = (res: any) => {
    dialogForm.value.donatorAvatar = res;
    upload.value!.clearFiles(); // 清除已上传文件
};

/** 查看捐赠记录信息 */
const handleViewDonationRecords = (row: any) => {
    recordDialogVisible.value = true;
    adminApi.getDonationRecordsByDonatorId({ donatorId: row.donatorId }).then((res: any) => {
        if (res) {
            donationRecordsData.value = res;
        }
    });
};
</script>

<style scoped lang="less">
@import "./css/tableForm.less";
</style>